package cn.tradewin.pmp.services.download.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.tapestry5.services.Response;

import cn.tradewin.common.util.MimeSymbols;
import cn.tradewin.pmp.services.download.OutputStreamResponse;

public class GeneralOutputStreamResponse implements OutputStreamResponse {

	private final String filename;
	
	public GeneralOutputStreamResponse(String filename) {
		System.out.println("**********filename***************" + filename);
		this.filename = filename;
	}
	
	@Override
	public String getContentType() {
		return MimeSymbols.APPLICATION_ANY;
	}

	@Override
	/**
	 * OutputStream will close by itself, no need to close it.
	 */
	public void writeToStream(OutputStream out) throws IOException {
		File file = new File(filename);
		if (file.exists() && file.isFile()) {
			long size = file.length();
			if (size > 0) {
				byte[] buf = new byte[4096];
				InputStream in = new BufferedInputStream(new FileInputStream(file), 4096);
				int readSize = 0;
				while ((readSize = in.read(buf)) != -1) {
					out.write(buf, 0, readSize);
				}
				in.close();
				out.close();
			}
		}
	}

	@Override
	public void prepareResponse(Response response) {
		try {
			String output = new File(filename).getName();
			// 如果不设定该header的值，就会直接在浏览器上显示的内容。
			response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode(output, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

}
